const http = require("http");
const fs = require("fs");
const { URL } = require("url");
const path = require("path");
http.createServer((req, res) => {
    let urlObj = new URL(req.url, "http://localhost:8081/")
    let pathName = urlObj.pathname;
    if (pathName == '/') {
        let fileContent = fs.readFileSync("./index.html");
        res.writeHead(200, { "Content-type": "text/html;charset=utf8" });
        res.end(fileContent);
    }
    else if (pathName == "/upload") {
        let str = ""
        req.setEncoding("binary");
        req.on("data", (chunk) => {
            str += chunk;
        })
        req.on("end", () => {
            let arr = str.split("\r\n");
            arr = arr.slice(4);
            let imgStr = arr.join("\r\n");
            let filePath = path.join(__dirname, "/upload/6.png")
            fs.writeFileSync(filePath, imgStr, { "encoding": "binary" });
            res.end(JSON.stringify({ "status": "ok" }))
        })
    }
    else if (pathName == "/list") {
        let fileContent = fs.readFileSync("./list.html");
        res.writeHead(200, { "Content-type": "text/html;charset=utf8" });
        res.end(fileContent);
    }
    else if (pathName == "/getlist") {
        let dirPath = path.join(__dirname, "/upload");
        const fileList = fs.readdirSync(dirPath);
        let dataList = []
        fileList.forEach(file => {
            dataList.push(file);
        })
        dataList = JSON.stringify(dataList);
        res.end(dataList);
    }
}).listen(8081);

console.log("server is listening 8081");